//
//  JCCSacnResultViewController.swift
//  剂查查
//
//  Created by shoubin tao on 2024/12/8.
//  Copyright © 2024 shipin. All rights reserved.
//

import CommonTools
import UIKit
import TYUIKit
import CJMobileAd

class JCCScanResultInfoModel {
    var grade: String = "A"
    var name: String = ""
    var data_image:String = ""
    var data_specs:String = ""
    var grade_title:String = ""
    var calorie_num :String = ""
    var sugar_num:String = ""
    var code:String = ""
    init(dict: [String: Any]) {
        self.grade = dict["grade"] as? String ?? ""
        self.name = dict["name"] as? String ?? ""
        self.data_image = dict["data_image"] as? String ?? ""
        self.data_specs = dict["data_specs"] as? String ?? ""
        self.grade_title = dict["grade_title"] as? String ?? ""
        self.sugar_num = dict["sugar_num"] as? String ?? ""
        self.calorie_num = dict["calorie_num"] as? String ?? ""
        self.code = dict["code"] as? String ?? ""
    }
}
class JCCScanResultNutritionCell:UITableViewCell{
    @IBOutlet weak var caLabel: UILabel!
    
    @IBOutlet weak var nutritionBottomView: UIView!
    @IBOutlet weak var sugarLabel: UILabel!
    override func layoutSubviews() {
        
    }
    override class func setValue(_ value: Any?, forUndefinedKey key: String) {
    }
}

class JCCScanResultZeroCell:UITableViewCell {
    
    override func layoutSubviews() {
        
    }
}
class JCCScanResultAdditiveCell:UITableViewCell {
    
    @IBOutlet weak var headRadioIconView: UIView!
    @IBOutlet weak var headLbl: UILabel!
    @IBOutlet weak var headTipsView: UIView!
    @IBOutlet weak var headTipsLbl: UILabel!
    @IBOutlet weak var itemBgImgView: UIImageView!
    @IBOutlet weak var itemBgView: UIView!

    override func layoutSubviews() {
        
    }
    
    public func createTipsView(_ title: String,_ color: UIColor?=nil) -> UIView {
        let view = UIView()
        view.layer.cornerRadius = 3.0
        view.layer.borderWidth = 1.0
        view.layer.borderColor = color?.cgColor ?? UIColor.lightGray.cgColor
        view.backgroundColor = color ?? .lightGray
        let lbl = UILabel()
        lbl.text = title
        lbl.font = .systemFont(ofSize: 11)
        lbl.textColor = color ?? .lightGray
        
        
        return view
    }
    
    public func createItemView(_ title: String, tips:[String]) -> UIView {
        let view = UIView()
        let radioView = UIView()
        radioView.backgroundColor = .green
        radioView.layer.cornerRadius = 3.0
        view.addSubview(radioView)
        
        
        return view
    }
}
class JCCScanResultTopCell:UITableViewCell{
    @IBOutlet weak var companyLabel: UILabel!
    @IBOutlet weak var gradeLabel: UILabel!
    
    @IBOutlet weak var gradeDescribeLabel: UILabel!
    @IBOutlet weak var numberLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var leftImageView: UIImageView!
    @IBOutlet weak var bgView: UIView!
    
    override func layoutSubviews() {
        bgView.layer.cornerRadius = 11
    }
}

class JCCScanResultViewController:UIViewController, UITableViewDelegate, UITableViewDataSource,CJBannerAdDelegate {

    var resultDict: [String:Any] = [:]
    var infoModel:JCCScanResultInfoModel =  JCCScanResultInfoModel(dict: [:])
    var additiveHeigh = 130.0
    var additiveSectionNum = 0
    var item_list:[[String:Any]] = [];
    
    @IBOutlet weak var tableView: UITableView!
    var bannerAd : CJBannerAd?
    var bannerView : UIView = UIView()
    
    
    func bannerAd(onShow bannerAd: Any) {
        print("onShow")
    }
    
    func bannerAd(onClicked bannerAd: Any) {
        print("onClicked")
    }
    
    func bannerAd(onClosed bannerAd: Any) {
        print("onClosed")
    }
    
    func bannerAdDidLoad(_ bannerView: UIView, resourceId: String) {
        self.bannerView.addSubview(bannerView)
    }
    
    func bannerAdLoadFailed(_ bannerAd: Any, error: any Error) {
        print("bannerAdLoadFailed\(error)")
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 1)
        {
            if(additiveSectionNum != 0){
                return additiveSectionNum
            }
        }
        return 1
    }
    func getHeaderView (title:String,subTitle:String,width:CGFloat)->UIView {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: 79))
         
        let lineView = UIView(frame: CGRect(x: 30, y: 31, width: 3, height: 17))
        lineView.backgroundColor = UIColor.init(hex: "#00B9FF")
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = CGRect(x: 11, y: 0, width: WIDTH-22, height: 79)
        gradientLayer.endPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.startPoint = CGPoint(x: 1, y: 0.5)
        gradientLayer.setTopCorners(radius: 11)
        gradientLayer.colors = [UIColor.init(hex:"#00D9CA").cgColor, UIColor.init(hex:"#5089FA").cgColor] // 渐变色设置为红色到蓝色
        bgView.layer.insertSublayer(gradientLayer, at: 0)
        bgView.addSubview(lineView)
        
        let title1: UILabel = UILabel.init(frame: CGRect(x: 39, y: 22, width: width, height: 35))
        title1.text = title
        title1.textColor = .white
        title1.font = UIFont.boldSystemFont(ofSize: 18.7)
        bgView.addSubview(title1)
        
        let title2: UILabel = UILabel.init(frame: CGRect(x: title1.frame.maxX+6, y: 22, width: 265, height: 35))
        title2.text = subTitle
        title2.textColor = .white
        title2.font = UIFont.boldSystemFont(ofSize: 15.4)
        bgView.addSubview(title2)
        return bgView
    }
    func sugarStep (num:Double) -> Int {
        if (num >= 0 && num < 9){
            return 5555
        }else if (num >= 9 && num < 18){
            return 6666
        }else if (num >= 18 && num < 31){
            return 7777
        }else if (num >= 31 && num < 45){
            return 8888
        }
        return 8888
    }
    func calorieStep (num:Double) -> Int {
        if (num >= 0 && num < 160){
            return 1111
        }else if (num >= 160 && num < 350){
            return 2222
        }else if (num >= 350 && num < 560){
            return 3333
        }else if (num >= 560 && num < 800){
            return 4444
        }
        return 4444
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if (section == 0 ) {
            return UIView()
        }
        else {
            if (section == 1){
                return getHeaderView(title: "添加剂", subTitle: "以下为AI识别，暂未经过人工仅供参考",width: 60)
            }else if (section == 2){
                return getHeaderView(title: "营养成分", subTitle: "此项不参与等级计算",width: 80)
            }
            else {
                return getHeaderView(title: "同类高分产品", subTitle: "",width: 120)
            }
        
        }
        
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 0 :79
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0){
            let cell:JCCScanResultTopCell = tableView.dequeueReusableCell(withIdentifier: "JCCScanResultTopCell", for: indexPath) as! JCCScanResultTopCell
            cell.nameLabel.text = infoModel.name
            cell.numberLabel.text = infoModel.data_specs
            cell.leftImageView.setImageUrl(url: infoModel.data_image)
            cell.companyLabel.text = infoModel.grade_title
            return cell
        }else if (indexPath.section == 1) {
            if additiveSectionNum == 0 {
                let cell:JCCScanResultZeroCell = tableView.dequeueReusableCell(withIdentifier: "JCCScanResultZeroCell", for: indexPath) as! JCCScanResultZeroCell
                return cell
            } else {
                let item = item_list[indexPath.row]
                let grade = item["grade"] as! String
                let gradeColor = jcc_gradeColor(grade:grade )
                let name = item["name"] as! String
                let items = item["item"] as! [[String:Any]]
                let cell:JCCScanResultAdditiveCell = tableView.dequeueReusableCell(withIdentifier: "JCCScanResultAdditiveCell", for: indexPath) as! JCCScanResultAdditiveCell
                cell.itemBgImgView.layer.cornerRadius = 14
                cell.headLbl.text = grade
            
                cell.headTipsLbl.text = " \(name) "
                cell.headTipsLbl.textColor = gradeColor
                cell.headTipsLbl.layer.borderColor = gradeColor?.cgColor
                cell.headTipsLbl.layer.borderWidth = 1
                cell.headTipsLbl.layer.cornerRadius = 4
                cell.headRadioIconView.layer.cornerRadius = 6
                cell.headRadioIconView.backgroundColor = gradeColor
                for (index, subItem) in items.enumerated() {
                    let view = UIView(frame:CGRect(x: 0, y: CGFloat(index)*60.0, width: WIDTH, height: 60))
//                    view.backgroundColor = .red
                    //圆圈
                    let circle = UIView(frame:CGRect(x: 0, y: 8, width: 6, height: 6))
                    circle.layer.cornerRadius = 6
                    circle.backgroundColor = gradeColor
                    view.addSubview(circle)
                    //文字
                    let titleLabel = UILabel(frame:CGRect(x: circle.frame.maxX+7.5, y: 0, width: 300, height: 20))
                    titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
                    titleLabel.text = subItem["name"] as? String
                    view.addSubview(titleLabel)
                    
                    //提示
                    let tipBtn = UIButton(frame:CGRect(x: WIDTH - 75, y: 17, width: 17, height: 17))
                    tipBtn.setImage(UIImage(named: "jcc_more_icon"), for: .normal)
                    view.addSubview(tipBtn)
                    
                    //tip文字
                    let titleTipLabel = UILabel(frame:CGRect(x: circle.frame.maxX+7.5, y: titleLabel.frame.maxY+12, width: 300, height: 20))
                    titleTipLabel.font = UIFont.boldSystemFont(ofSize: 11)
                    titleTipLabel.textColor = UIColor.init(hex: "#8F8F8F")
                    titleTipLabel.layer.borderWidth = 1
                    titleTipLabel.layer.borderColor = UIColor.init(hex: "#8F8F8F").cgColor
                    titleTipLabel.text = " \(subItem["effect"] as? String ?? "无" ) "
                    titleTipLabel.layer.cornerRadius = 4
                    titleTipLabel.sizeToFit()
                    view.addSubview(titleTipLabel)
                    
                    cell.itemBgView.addSubview(view)
                }

                return cell
            }
        }else if (indexPath.section == 2) {
            
            let cell:JCCScanResultNutritionCell = tableView.dequeueReusableCell(withIdentifier: "JCCScanResultNutritionCell", for: indexPath) as! JCCScanResultNutritionCell
            cell.caLabel.text = "\(infoModel.calorie_num) Kcal"
            cell.sugarLabel.text = "\(infoModel.sugar_num) Kcal"
//            cell.nutritionBottomView.layer.setBottomCorners(radius: 20)
            let calorieStep = self.calorieStep(num: Double(infoModel.calorie_num) ?? 0)
            let sugarStep = self.sugarStep(num: Double(infoModel.sugar_num ) ?? 0)
            cell.viewWithTag(calorieStep)?.isHidden = false
            cell.viewWithTag(sugarStep)?.isHidden = false
            return cell
        }
        else {
            return UITableViewCell()
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath.section == 0){
            return 174
        }else if (indexPath.section == 1){
            let item = item_list[indexPath.row]
            let items = item["item"] as! [[String:Any]]
            return 40+Double(items.count * 60)
        }else if (indexPath.section == 2){
            return 234
        }else{
            return 0
        }
                    
    
    }

    override func viewWillAppear(_ animated: Bool) {
        
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
//        self.navigationController?.navigationBar.isHidden = false
    }
    override func viewDidLoad() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        let dict = resultDict["info"] as! [String:Any]
        self.infoModel = JCCScanResultInfoModel(dict: dict)
        self.item_list = resultDict["item_list"] as? [[String:Any]] ?? []
        additiveSectionNum = self.item_list.count
        
        self.tableView.reloadData()
        
        setTitle("扫码结果")
        setupNav()
        
        
        bannerView = UIView(frame: CGRectMake(0, 100, screenWidth(), UIScreen.main.bounds.size.width*80/screenWidth()))
        view.addSubview(bannerView)
        
        bannerAd = CJBannerAd(resourceId: "017fad6fe3160b9f", rootViewController: self, rect: CGRectMake(10, 10, screenWidth() - 20, UIScreen.main.bounds.size.width*50/320))
        bannerAd?.delegate = self
        bannerAd?.loadData()
    }
    

    func setupNav() {
        let arr = [("jcc_menu_2", ""), ("jcc_menu_1", "jcc_scan_collected"), ("jcc_menu_3", "")]
        let rightView = UIView(backgroundColor: .clear, in: nil, frame: CGRect(x: 0, y: 0, width: 96, height: 44))
        for (i, (nor, sel)) in arr.enumerated() {
            let btn = NoHighlightedButton(image: UIImage(named: nor)?.byResize(to: CGSize(width: 19, height: 19)), title: nil, titleColor: nil, font: nil, in: rightView, frame: CGRect(x: (19 + 19) * Double(i), y: 7.5, width: 19, height: 19))
            if !sel.isEmpty {
                btn.setImage( UIImage(named: sel)?.byResize(to: CGSize(width: 19, height: 19)), for: .selected)
            }
            btn.addBlock(for: .touchUpInside) {[unowned self] _ in
                if !sel.isEmpty {
                    btn.isSelected = !btn.isSelected
                }
                if i == 0 {
                    modifyAction()
                }
                else if i == 1 {
                    if btn.isSelected {
                        collectAction()
                    }
                    else {
                        
                    }
                }
                else if i == 2 {
                    XWWeChatOpenSDKBridgeProtocolImpl.shared.sendShareReq()
                }
            }
        }
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightView)
    }
    
    func modifyAction() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        if let viewController = storyboard.instantiateViewController(withIdentifier: "JCCErrorModifyViewController") as? JCCErrorModifyViewController {
            viewController.infoModel = infoModel
            TY_TopViewController().navigationController?.pushViewController(viewController, animated: true)
        }
        
    }
    func collectAction() {
        JCCNet.setFavorite(isAdd: true, gcodes: [infoModel.code]) { model, error in
            
        }
    }
    
}
